#include <stdio.h>
#include <string.h>

#include "PTLock.h"
#include "args.h"
// #include "interface.h"
#ifdef DEBUG
#include <assert.h>
#endif
#include <simd.h>
#include <slave.h>
#include <sys/wait.h>

#define my_atomic_add(_new_, _addr_)                                                \
    {                                                                               \
        asm volatile("faal   %0,0(%1)\n\t" : "=r"(_new_) : "r"(_addr_) : "memory");  }

unsigned long slave_get_ticket(unsigned long *head)
{
    unsigned long old_head;
    my_atomic_add(old_head, head);  // old_head返回的是旧值还是新值，应该是旧值
    // printf("%lu,%lu\n",old_head,*head);
    return old_head;
}

unsigned long slave_wait(unsigned long ticket)
{
    while (waitq[ticket % size] < ticket)
        ;
}
void slave_lock() { slave_wait(get_ticket(&(head))); }
void slave_unlock()
{
    unsigned long index = (tail) % (size);
    waitq[index] = tail++;
}
